from django.shortcuts import render_to_response, get_object_or_404
from django.template import RequestContext
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from blog import config
from blog.HttpErrorHandler import HttpError403
from blog.models import Post

def list(request):
    post_list = Post.get_by_user(request.user)
    paginator = Paginator(post_list, config.MAX_ITEMS_PER_PAGE)
    p = request.GET.get('page', 1)

    try:
        posts = paginator.page(p)
    except PageNotAnInteger:
        posts = paginator.page(1)
    except EmptyPage:
        posts = paginator.page(paginator.num_pages)

    return render_to_response(
        'blog/post/list.html',
        {'posts': posts},
        RequestContext(request)
    )

def detail(request, post_id):
    post = get_object_or_404(Post, pk = post_id)

    if not post.public and not request.user.has_perm('blog.view_private_posts'):
        return HttpError403(request)

    return render_to_response(
        'blog/post/detail.html',
        {'post' : post},
        RequestContext(request)
    )